package com.zhehekeji.opsys.api.plugin.wechat.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhehekeji.opsys.api.plugin.wechat.enm.EventType;
import com.zhehekeji.opsys.api.plugin.wechat.enm.MsgType;
import com.zhehekeji.opsys.api.plugin.wechat.service.WechatCustomManagerService;
import com.zhehekeji.opsys.api.plugin.wechat.util.XmlUtils;

/**
 * @author chenweiliu chenwei.liu@163.com
 * @ClassName WechatCustomListenCtrl
 * @Description TODO
 * @date 2018-2-1   下午3:20:07
 */
@Controller
@RequestMapping("/wechatCustomListen")
public class WechatCustomListenCtrl {

    private static final Logger logger = LoggerFactory.getLogger(WechatCustomListenCtrl.class);
    @Autowired
    private WechatCustomManagerService wechatCustomManagerService;

    @RequestMapping(value = "/receiveMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void receiveMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        boolean isPost = request.getMethod().toLowerCase().equals("post");
        String rsp = "";
        PrintWriter out = null;
        try {
            if (isGet) {
                rsp = checkSignature(request, response);
            } else {
                if (isPost) {
                    rsp = handlerMsg(request, response);
                }
            }
        } catch (Exception e) {
            logger.error("处理消息失败", e);
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
        }
        response.getWriter().write(rsp);
    }

    private String checkSignature(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        String inMsg = "checkSignature [signature=" + signature + ", timestamp=" + timestamp + ", nonce=" + nonce + ", echostr=" + echostr + "]";
        logger.info(inMsg);
        String rspStr = "";
        if (!StringUtils.isBlank(echostr)) {
            rspStr = echostr;
        }
        return rspStr;
    }

    private String handlerMsg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String rspStr = StringUtils.EMPTY;
        Map<String, String> reqMap = XmlUtils.xmlToMap(request);
        String msgType = reqMap.get("MsgType");
        String event = reqMap.get("Event");
        String eventKey = reqMap.get("EventKey");
        String toUserName = reqMap.get("ToUserName");
        String fromUserName = reqMap.get("FromUserName");
        String inMsg = "handlerMsg [msgType=" + msgType + ", event=" + event + ", eventKey=" + eventKey + ", toUserName=" + toUserName + ", fromUserName=" + fromUserName + "]";
        logger.info(inMsg);
        if (StringUtils.isBlank(msgType)) {
            return rspStr;
        }
        //场景值不加密：用户账号$红包金额$发送限制次数$活动周期限制
        //场景值加密：加密密文
        if (StringUtils.isBlank(eventKey)) {
            return rspStr;
        }
        if (!msgType.equals(MsgType.EVENT.getType())) {
            return rspStr;
        }
        if (StringUtils.isBlank(event)) {
            return rspStr;
        }
        if (!event.equals(EventType.SUBSCRIBE.getType()) && !event.contains(EventType.SCAN.getType())) {
            return rspStr;
        }
        if (event.equals(EventType.SUBSCRIBE.getType())) {
            eventKey = eventKey.replace("qrscene_", "");
        }
        synchronized (WechatCustomListenCtrl.class) {
            rspStr = wechatCustomManagerService.handler(msgType, event, eventKey, toUserName, fromUserName);
        }
        return rspStr;
    }
}

